<template>
    <div class="crowd-manage-main">
        <ZwSearchForm row-num="2" :option="searchOption" @search="search" @reset="reset" @expand="expandHandle" />
        <ZwTable
            ref="tableRef"
            class="table-box"
            tab-h="initial"
            :option="tableOption"
            :row-key="getRowKey"
            :fetch-params="state.searchParams"
            :fetch-api="fetchApi()">
            <template #headerOperateLeft>
                <div class="left">
                    <span>最近人群包更新时间：{{ updateTime }}</span>
                    <span class="sync_hronize" @click="getSyncFun">
                        <el-icon v-if="loading" class="is-loading"><Loading /></el-icon>
                        <el-icon v-else class="sync_icon"><RefreshRight /></el-icon>
                        {{ loading ? '更新中...' : '更新' }}
                        <el-tooltip class="box-item" placement="top">
                            <template #content>
                                <div style="width: 150px">
                                    未锁定的人群包将重新计算人群，并更新至对应的应用端（如AI外呼、短信）
                                </div>
                            </template>
                            <el-icon class="help_icon" color="#ccc">
                                <QuestionFilled style="width: 16px; height: 16px" />
                            </el-icon>
                        </el-tooltip>
                    </span>
                </div>
            </template>
            <template #headerOperate>
                <div class="gc-content">
                    <div class="right">
                        <el-button @click="handlerAdvanced()">高级配置</el-button>
                        <el-button v-auth="'ADD_CROWD_MANAGE'" type="primary" @click="handlerCreated">
                            新建人群包
                        </el-button>
                    </div>
                </div>
            </template>
        </ZwTable>
        <NameList :id="nameListId" ref="nameListRef" v-model="isNameListShow" />
        <OutboundTask ref="outboundTaskRef" />
        <ZWDeleteDialog ref="deleteDialogRef" @submit="deleteSubmit" />
        <Dialog :app-dialog="appDialog">
            <div class="refresh">
                更新人群包频次：每
                <el-input-number v-model="formData.params.execute_time" :min="1" :precision="0" class="inputNumber" />
                <el-select
                    v-model="formData.params.execute_time_type"
                    class="cust_message"
                    placeholder="请选择客户阶段">
                    <el-option value="2" label="小时">小时</el-option>
                    <el-option value="3" label="天">天</el-option>
                </el-select>
                <el-time-select
                    v-if="formData.params.execute_time_type == '3'"
                    v-model="formData.params.execute_time_hour"
                    class="time_pick"
                    :clearable="false"
                    start="00:00"
                    end="23:50"
                    step="00:10"
                    placeholder="选择时间" />
                更新非锁定状态人群包数量
                <div v-show="isShow" class="tips">请输入更新人群包时间</div>
            </div>
        </Dialog>
    </div>
</template>

<script lang="tsx">
import { defineComponent } from 'vue';
// 定义name专用script标签
// eslint-disable-next-line vue/component-definition-name-casing
export default defineComponent({ name: 'CUSTOMER_GROUP_MANAGE_CROWD_MANAGE' });
</script>

<script setup lang="tsx">
import { ref, reactive, onMounted, onActivated, computed } from 'vue';
import { ElMessage, ElButton } from 'element-plus';
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import ZWDeleteDialog from '@/components/ZWDeletdialog.vue';
import NameList from './components/NameList.vue';
import OutboundTask from './components/OutboundTask.vue';
import Dialog from '@/components/Dialog.vue';

import {
    getCrowdPackageList,
    crowdPackageDel,
    advancedSetup,
    getAdvanced,
    getAiAccountInfo,
    updatePackage
} from '@/api/customer/crowdManage/index';
import { getSyncTime } from '@/api/customerCenter/groupManage';
import { getCreateList } from '@/api/common';
import { deepCopy } from '@/utils/helper';
import { useRouter } from 'vue-router';
import { QuestionFilled } from '@element-plus/icons-vue';

const router = useRouter();

const tableRef = ref<any>(null);
const nameListRef = ref<any>(null);
const outboundTaskRef = ref<any>(null);
const deleteDialogRef = ref<any>(null);

const isNameListShow = ref<boolean>(false);
const isShow = ref<boolean>(false);
const nameListId = ref<any>('');
const updateTime = ref<any>('');

const delInfo = reactive<any>({
    crowd_package_id: ''
});

const requestFlag = ref<boolean>(false);
const currentParams = ref<any>(null);

const loading = ref<boolean>(false);
const formData = reactive<any>({
    module: 1,
    params: {
        execute_time: undefined,
        execute_time_type: '3', //2小时3天
        execute_time_hour: '23:00'
    }
});
const cancelHandel = () => {
    appDialog.visible = false;
};
const submitHandel = () => {
    if (!formData.params.execute_time) {
        isShow.value = true;
        return;
    } else {
        isShow.value = false;
    }
    advancedSetup(formData).then((res: any) => {
        ElMessage.success('设置成功！');
        appDialog.visible = false;
    });
};
const appDialog = reactive({
    visible: false,
    title: '高级配置',
    width: '700px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '保存'
});
const isAiHidden = ref<any>(2); // 1-显示 2-隐藏

const searchOption = computed(() => {
    return [
        {
            label: '人群包名称',
            name: 'name',
            type: 'input',
            clearable: true,
            placeholder: '请输入人群包名称搜索'
        },
        {
            label: '创建方式',
            name: 'crowd_set',
            type: 'select',
            clearable: true,
            placeholder: '请选择创建方式',
            optionList: [
                { name: '手机号上传', id: '1' },
                // { name: '企微群保存', id: 1 },
                { name: '客户筛选', id: 2 }
                // { name: '自动圈选', id: 3 }
            ],
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '创建人',
            name: 'create_user',
            value: [],
            multiple: true,
            type: 'select',
            filterable: true,
            placeholder: '请选择创建人',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    getCreateList({}).then((res: any) => {
                        const targetArr = res.map((item: any) => {
                            item.name = `${item.name}  (${item.phone}) `;
                            return item;
                        });
                        resolve(targetArr);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        }
    ];
});

const tableOption = [
    {
        prop: 'name',
        label: '人群包名称',
        minWidth: 150
    },
    {
        prop: 'total_qty',
        label: '总人数',
        width: 150
    },
    {
        prop: 'wx_user_qty',
        label: '微信触达用户数',
        width: 140
    },
    {
        prop: 'phone_num',
        label: '有效手机号数量',
        width: 160
    },
    {
        prop: 'crowd_set_value',
        label: '创建方式',
        width: 120
    },
    {
        prop: 'is_lock',
        width: 120,
        renderHeader: () => {
            return (
                <div class="label_box">
                    <span>锁定</span>
                    <el-tooltip
                        class="box-item"
                        vSlots={{
                            content: () => (
                                <div>
                                    <div style="width: 220px;line-height: 20px;">
                                        未锁定：如果筛选/规则计算结果发生变化，此人群包的名单也会实时更新；
                                    </div>
                                    <div style="width: 220px;line-height: 20px;">
                                        已锁定：如果筛选/规则计算结果发生变化，此人群包的名单不会发生变化。
                                    </div>
                                </div>
                            )
                        }}
                        placement="top">
                        <el-icon color="#ccc">
                            <QuestionFilled class="heard_icon" />
                        </el-icon>
                    </el-tooltip>
                </div>
            );
        },
        render({ row }: any) {
            return <div>{row.is_lock == 1 ? '未锁定' : '锁定'}</div>;
        }
    },
    {
        prop: 'create_user',
        label: '创建人',
        width: 200
    },
    {
        prop: 'create_time',
        label: '创建时间',
        minWidth: 200
    },
    {
        prop: 'operate',
        label: '操作',
        fixed: 'right',
        width: 290,
        isOperate: true,
        render({ row }: any) {
            return (
                <div class="zw-table__btn-box">
                    <ElButton size="small" onClick={() => handleDetails(row)} vAuth={'DEL'}>
                        删除
                    </ElButton>
                    <ElButton size="small" onClick={() => handlerEdit(row)} vAuth={'EDIT'}>
                        编辑
                    </ElButton>
                    <ElButton size="small" onClick={() => handlerLook(row)} vAuth={'VIEW'}>
                        查看
                    </ElButton>
                    <ElButton size="small" onClick={() => handlerNameList(row)} vAuth={'VIEW_NAME_LIST'}>
                        名单
                    </ElButton>
                    <ElButton size="small" onClick={() => handlerOutboundTask(row)} vAuth={'ADD_OUT_BOUND'}>
                        创建外呼任务
                    </ElButton>
                </div>
            );
        }
    }
];
const getSyncFun = () => {
    loading.value = true;
    updatePackage()
        .then((r: any) => {
            loading.value = false;
            getSyncTimeFun();
            ElMessage.success('更新成功');
        })
        .catch(() => {
            ElMessage.error('更新失败');
        });
};
const getSyncTimeFun = () => {
    getSyncTime({ sync_type: 140 }).then((r: any) => {
        updateTime.value = r.weiwork_synctime;
    });
};
getSyncTimeFun();
//高级配置
const handlerAdvanced = () => {
    isShow.value = false;
    getAdvanced({ module: 1 }).then((res: any) => {
        if (res) {
            formData.params.execute_time = res.params?.execute_time || undefined;
            formData.params.execute_time_type = res.params?.execute_time_type || '3';
            formData.params.execute_time_hour = res.params?.execute_time_hour || '23:00';
        }
        appDialog.visible = true;
    });
};
const defaultParams = {
    name: '', // 搜索
    crowd_set: '', // 创建方式
    create_user: [] // 创建人
};

const state = reactive({
    searchParams: deepCopy(defaultParams),
    searchHeight: '112px'
});

const getRowKey = (row: any) => {
    return row.id;
};

const search = (data: any) => {
    currentParams.value = data;
    tableRef.value.getTable().clearSelection();
    state.searchParams = deepCopy({ ...defaultParams, ...data });
};

const reset = () => {
    tableRef.value.getTable().clearSelection();
    state.searchParams = deepCopy({ ...defaultParams });
    currentParams.value = null;
};

/**
 * @description: 展开收起
 */
const expandHandle = (expand: boolean) => {
    state.searchHeight = expand ? '112px' : '64px';
};

const fetchApi = () => {
    return getCrowdPackageList;
};

const initAiAccountInfo = async () => {
    const res = await getAiAccountInfo();
    isAiHidden.value = res.is_hidden;
};
initAiAccountInfo();

const deleteSubmit = async () => {
    const params = {
        crowd_package_id: delInfo.crowd_package_id
    };
    const res = await crowdPackageDel(params);
    if (res) {
        ElMessage.success('删除成功');
        deleteDialogRef.value.appDialog.visible = false;
        tableRef.value.reload();
    }
};

const handleDetails = (val: any) => {
    delInfo.crowd_package_id = val.id;
    deleteDialogRef.value.content = '确认删除该人群包吗？';
    deleteDialogRef.value.appDialog.visible = true;
};

const handlerEdit = (val: any) => {
    router.push({
        path: '/customer/groupManage/crowdManage/detail',
        query: { type: 'edit', id: val.id }
    });
};

const handlerLook = (val: any) => {
    router.push({
        path: '/customer/groupManage/crowdManage/detail',
        query: { type: 'look', id: val.id }
    });
};

const handlerNameList = (val: any) => {
    // nameListRef.value.appDialog.visible = true
    // nameListRef.value.defaultParams.id = val.id
    nameListRef.value.state.searchParams.id = '';
    nameListRef.value.state.searchParams.id = val.id;
    nameListRef.value.appDialog.visible = true;
    nameListRef.value.baseInfo.name = `【${val.name}】的名单`;
    nameListRef.value.statList[0].num = val.total_qty;
    nameListRef.value.statList[1].num = val.phone_num;
    nameListRef.value.statList[2].num = val.wx_user_qty;
    isNameListShow.value = true;
};

const handlerOutboundTask = (val: any) => {
    const name = `【${val.name}】-- 创建外呼任务`;
    outboundTaskRef.value.formData.name = val.name;
    outboundTaskRef.value.formData.phone_num = val.phone_num;
    outboundTaskRef.value.formData.crowd_package_id = val.id;
    outboundTaskRef.value.appDialog.title = name;
    outboundTaskRef.value.appDialog.visible = true;
};

const handlerCreated = () => {
    router.push('/customer/groupManage/crowdManage/detail');
};

onActivated((val: any) => {
    tableRef.value.getTable().clearSelection();
    state.searchParams = { ...deepCopy(defaultParams), ...currentParams.value };
});
</script>
<style lang="scss" scoped>
.crowd-manage-main {
    height: calc(100vh - 142px);
    padding: 24px;
    border: 1px solid #eaeaea;
    border-radius: 4px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .zw-table {
        display: flex;
        flex-direction: column;
        flex: 1;
        overflow: hidden;

        :deep(.el-table) {
            flex: 1;

            .el-table__empty-block {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
        }
    }

    .refresh {
        padding: 40px 0;

        :deep(.cust_message_min) {
            width: 150px;
            margin: 0 10px;

            input {
                padding: 0 0 0 15px !important;
            }
        }

        .cust_message {
            width: 80px;
        }

        .time_pick {
            width: 110px;
            margin-left: 5px;
        }

        .inputNumber {
            width: 140px;
            margin-right: 5px;
        }

        .tips {
            color: red;
            padding: 10px 0 0 110px;
        }
    }

    .left {
        display: flex;

        .sync_hronize {
            display: flex;
            align-items: center;
            margin-left: 10px;
            color: #ff6b00;
            cursor: pointer;
        }

        span {
            font-size: 14px;
            font-family: STHeitiSC-Light, STHeitiSC;
            color: #33302d;
            line-height: 44px;
        }
    }
}

.help_icon {
    vertical-align: middle;
    margin-left: 5px;
    cursor: pointer;
}

:deep(.label_box) {
    display: flex;
    align-items: center;

    .heard_icon {
        width: 16px;
        height: 16px;
    }
}
</style>
